package com.jzg.jcptadmin.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.text.method.NumberKeyListener;
import android.text.method.ReplacementTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MD5Utils;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.adpter.OfflineDetectionAdapter;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.local.LocalData;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.FastOnlineData;
import com.jzg.jcptadmin.data.vo.OfflineDetectionData;
import com.jzg.jcptadmin.data.vo.User;
import com.jzg.jcptadmin.presenter.OffLineSearchByVINPresenter;
import com.jzg.jcptadmin.view.MyErrorLayout;
import com.jzg.jcptadmin.viewinterface.OffLIneSearchByVINInterface;
import com.jzg.template.refreshrecycleview.DividerItemDecoration;
import com.jzg.template.refreshrecycleview.RefreshBaseAdapter;
import com.jzg.template.refreshrecycleview.RefreshRecycleView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 搜索页面 （按照VIN搜索）
 */
public class OffLineSearchByVINActivity extends BaseActivity implements OffLIneSearchByVINInterface, RefreshRecycleView.OnStateChangeLstener {

    @Bind(R.id.cancel)
    TextView cancel;
    @Bind(R.id.content)
    AutoCompleteTextView searchText;
    @Bind(R.id.swipeRefresh)
    RefreshRecycleView fastOnlineRecycler;
    @Bind(R.id.ll_error)
    MyErrorLayout llError;
    @Bind(R.id.fast_empty_view)
    ViewStub fastEmptyView;
    List<String> vins;

    public OffLineSearchByVINPresenter presenter;

    private List<OfflineDetectionData.OffLineTaskListEntity> mDatas = new ArrayList<>();
    private OfflineDetectionAdapter adapter;

    private OfflineDetectionData.OffLineTaskListEntity currEntity;
    private User user;
    private String vin;

    private int PageIndex = 1;//页码

    /**
     * (0默认，1刷新，2加载)
     */
    private int operation = Constant.LISTVIEW_DEFAULT;

    //数据类型 2今日任务  3昨天任务  1全部任务 默认今日任务
    private int datetype = Constant.ALL_TASK;

    //点击全部状态的id  默认-2
    private String status = "-2";

    /**
     * 是从那个界面挑传过来的
     * 1、表示从快速线上评估界面跳转过来的，
     * 2、表示从专业线下界面跳转过来的
     */
    private int source = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_vin);
        ButterKnife.bind(this);
        presenter = new OffLineSearchByVINPresenter(DataManager.getInstance());
        presenter.attachView(this);

        initViews();

    }

    private void  initViews(){
        user = appContext.getUser();
//        source = getIntent().getBundleExtra().getIntExtra("source",-1);
        source = getIntent().getBundleExtra("bd").getInt("source",-1);

        filterEditText();

        vins = new ArrayList<String>();

        ArrayAdapter arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, vins);
        searchText.setAdapter(arrayAdapter);
        searchText.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Intent intent = new Intent();
                TextView tv = (TextView) view;
                vin = tv.getText().toString();
//                detectionEvaluationPresenter.loadData();
            }
        });

        llError.setOnReloadClickLintener(new MyErrorLayout.ReloadClickLintener() {
            @Override
            public void onReload() {
                llError.setVisibility(View.GONE);
                PageIndex=1;
//                detectionEvaluationPresenter.loadData();
                fastOnlineRecycler.setRefreshing(true);
//                    presenter.loadSearchByVinData(user.getUserId() + "", datetype + "", status + "", operation + "", "","",vin,source);
                presenter.loadOffLineSearchByVinData("");

            }

        });

        searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (v.getText().toString().length() < 5) {
                    MyToast.showShort("请输入至少5位VIN");
                    return false;
                }
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    MobclickAgent.onEvent(OffLineSearchByVINActivity.this, "dianji_chaxun");
                    fastOnlineRecycler.setRefreshing(true);
                    presenter.resetPageIndex();
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    getCurrentFocus().getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
//                    VinInfo carInfo = new VinInfo();
                    vin = v.getText().toString().toUpperCase();
//                    carInfo.setVin(vin);
//                    carInfo.save();
                    vins.add(vin);
//                    detectionEvaluationPresenter.loadData();
//                        presenter.loadSearchByVinData(user.getUserId() + "", datetype + "", status + "", operation + "", "","",vin,source);
                     presenter.loadOffLineSearchByVinData("");

                    return true;
                }
                return false;
            }
        });


        fastOnlineRecycler.setColorSchemeColors(Color.parseColor(Constant.ACTIVITY_REFRESHCOLOR));
        fastOnlineRecycler.setOnStateChangeLstener(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        fastOnlineRecycler.mRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        fastOnlineRecycler.setLayoutManager(linearLayoutManager);
        adapter = new OfflineDetectionAdapter(this, mDatas);
        fastOnlineRecycler.setAdapter(adapter);
        adapter.setOnItemClickLitener(new RefreshBaseAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                    if (position < mDatas.size()) {
                        currEntity = mDatas.get(position);
//                    if("2".equals(currEntity.getTaskType())){//六张直接进详情
//                        loadDetail();
//                        return;
//                    }
                        String operation = currEntity.getMessageOperation();
                        final Integer op = Integer.valueOf(operation);
                        SweetAlertDialog sweetDialog = new SweetAlertDialog(OffLineSearchByVINActivity.this);
                        String title = "";
                        String content = "";
                        String confirmText = "";
                        String cancelText = "";
                        SweetAlertDialog.OnSweetClickListener confirmListener = new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                                String status = currEntity.getStatus();
                                if (op == 4 || op == 8) {
                                    presenter.offLineclaimTask(String.valueOf(appContext.getUser().getUserId()), currEntity.getID(), "type", "ShenHeRenling",op);
                                } else if (op == 3) {
                                    presenter.offLineclaimTask(String.valueOf(appContext.getUser().getUserId()), currEntity.getID(), "type", "renling", -1);
                                } else {
                                    if ("2".equals(status)) {
                                        loadOffLineDetail();
                                    } else {
                                        presenter.offLineclaimTask(String.valueOf(appContext.getUser().getUserId()), currEntity.getID(), "type", "renling", op);
                                    }
                                }

                            }
                        };
                        SweetAlertDialog.OnSweetClickListener cancelListener = new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.dismiss();
                            }
                        };
                        if (op != 6) {
                            switch (op) {
                                case 1://待评估
                                    title = "确认任务";
                                    content = "VIN:" + currEntity.getVin() + "\r\n" + "\r\n" + "城市:" + currEntity.getProvName() + "-" + currEntity.getCityName();
                                    confirmText = "确定";
                                    cancelText = "取消";
                                    break;
                                case 2://待评估，被别人退回
                                    content = "此订单之前由" + currEntity.getNickname() + "退回！是否操作此订单？" + "\r\n" + "\r\n" +
                                            (TextUtils.isEmpty(currEntity.getTaskBackReason()) ? "" : currEntity.getTaskBackReason());
                                    confirmText = "确定";
                                    cancelText = "取消";
                                    break;
                                case 3://已认领过 （总部评估师）
                                    content = "此订单已被" + currEntity.getNickname() + "认领！是否操作此订单？";
                                    confirmText = "确定";
                                    cancelText = "取消";
                                    break;
                                case 4://总部审核（被驳回过）
                                    content = "此订单之前由" + currEntity.getShenheName() +
                                            "审核驳回！是否操作此订单？" + "\r\n" + "\r\n" +
                                            (TextUtils.isEmpty(currEntity.getAppraiseBackReason()) ? "" : currEntity.getAppraiseBackReason());
                                    confirmText = "确定";
                                    cancelText = "取消";
                                    break;
                                case 5://已认领（非总部）
                                    content = "此订单已被" + currEntity.getNickname() + "认领!";
                                    confirmText = "关闭";
                                    break;
                                case 7://已被XXX审核！
                                    content = "此订单正在被" + currEntity.getShenheName() + "审核!";
                                    confirmText = "关闭";
                                    break;
                                case 8://弹出是否确认审核
                                    title = "确认审核";
                                    content = "是否确认审核该订单?";
                                    confirmText = "确定";
                                    cancelText = "取消";
                                    break;
                            }
                            sweetDialog.setTitleText(title);
                            if (!TextUtils.isEmpty(title)) {
                                sweetDialog.setTitleText(title);
                            }
                            if (!TextUtils.isEmpty(content)) {
                                sweetDialog.setContentText(content);
                            }
                            if (!TextUtils.isEmpty(confirmText)) {
                                sweetDialog.setConfirmText(confirmText);
                                if (op == 5 || op == 7) {
                                    sweetDialog.setConfirmClickListener(cancelListener);
                                } else {
                                    sweetDialog.setConfirmClickListener(confirmListener);
                                }
                            }
                            if (!TextUtils.isEmpty(cancelText)) {
                                sweetDialog.setCancelText(cancelText);
                                sweetDialog.setCancelClickListener(cancelListener);
                            }
                            sweetDialog.show();
                        } else {//op==6 直接进详情
                            loadOffLineDetail();
                        }
                    }
            }
        });
    }

    @OnClick({R.id.cancel})
    public void viewClick(View view){
        switch (view.getId()){
            case R.id.cancel:
                LocalData.isRefresh = true;//解决 返回的列表不刷新
                finish();
                break;
        }
    }

    /**
     * 点击返回键的时候
     * 线下界面的刷型标识设置为ture
     */
    @Override
    public void onBackPressed() {
        LocalData.isRefresh = true;
        super.onBackPressed();
    }

    private void loadOffLineDetail(){
        LocalData.isRefresh = true;
        Intent intent = new Intent(OffLineSearchByVINActivity.this, TaskViewActivity.class);
        intent.putExtra(Constant.ACTIVITY_OFFINEID, currEntity.getID());
        startActivity(intent);
    }

    /**
     * 设置vin的过滤条件
     */
    private void filterEditText() {
        searchText.requestFocus();
        searchText.setKeyListener(new NumberKeyListener() {
            @Override
            protected char[] getAcceptedChars() {
                // TODO Auto-generated method stub
                return new char[]{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
                        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',
                        'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P',
                        'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            }

            @Override
            public int getInputType() {
                // TODO Auto-generated method stub
                return 1;
            }
        });
        searchText.setTransformationMethod(new InputLowerToUpper());
    }

    @Override
    public void onRefresh() {
        if (TextUtils.isEmpty(searchText.getText().toString())||searchText.getText().toString().length() < 5||TextUtils.isEmpty(vin)) {
            fastOnlineRecycler.setRefreshing(false);
            MyToast.showShort("请输入至少5位VIN");
            return ;
        }
            presenter.resetPageIndex();
            operation = Constant.LISTVIEW_DEFAULT;
            if (appContext.isNetWork) {
//                presenter.loadSearchByVinData(user.getUserId() + "", datetype + "", status, operation + "", "", "", vin,source);
                presenter.loadOffLineSearchByVinData("");
            } else {
                fastOnlineRecycler.setRefreshing(false);
            }

    }

    @Override
    public void onBottom() {

           operation = Constant.LISTVIEW_LOAD_MORE;
           if (mDatas.size() > 0) {
//               presenter.loadOffineDataNew(user.getUserId() + "", datetype + "", status + "", Operation + "", mDatas.get(mDatas.size() - 1).getID());
               presenter.loadOffLineSearchByVinData(""+mDatas.get(mDatas.size() - 1).getID());
           } else {
               fastOnlineRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_FAILED);
           }

    }

    public class InputLowerToUpper extends ReplacementTransformationMethod {
        @Override
        protected char[] getOriginal() {
            char[] lower = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
            return lower;
        }

        @Override
        protected char[] getReplacement() {
            char[] upper = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
            return upper;
        }

    }

    @Override
    public void showData(FastOnlineData fastOnlineData) {

    }

    @Override
    public void showMoreData(FastOnlineData fastOnlineData) {

    }

    @Override
    public void showDetail(CarDetails carDetails, String type) {

    }

    @Override
    public void claimSucceed() {
            loadOffLineDetail();
    }

    @Override
    public void claimFailed(String message) {

            SweetAlertDialog dialog = new SweetAlertDialog(OffLineSearchByVINActivity.this);
            dialog.setTitleText(message);
            dialog.setConfirmText("关闭");
            dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                }
            });
            dialog.show();
            onRefresh();
    }

    @Override
    public void dataFailed(String message) {

    }

    @Override
    public void qiangdan(final String taskId, String msg) {
            SweetAlertDialog dialog = new SweetAlertDialog(OffLineSearchByVINActivity.this);
            dialog.setTitleText(msg);
            dialog.setConfirmText("确认");
            dialog.setCancelText("取消");
            dialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                    presenter.claimTask(String.valueOf(appContext.getUser().getUserId()), taskId, "type", "renling", -1);
                }
            });
            dialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sweetAlertDialog) {
                    sweetAlertDialog.dismiss();
                }
            });
            dialog.show();
    }

    @Override
    public void showOffLineDataSuccess(OfflineDetectionData offlineDetectionData) {
        dismissDialog();
        fastOnlineRecycler.setRefreshing(false);
        if (offlineDetectionData.getOffLineTaskList()!=null&&offlineDetectionData.getOffLineTaskList().size() == 0) {
            fastEmptyView.setVisibility(View.VISIBLE);
            llError.setVisibility(View.GONE);
            fastOnlineRecycler.setVisibility(View.GONE);
        } else {
            fastEmptyView.setVisibility(View.GONE);
            llError.setVisibility(View.GONE);
            fastOnlineRecycler.setVisibility(View.VISIBLE);
            if (operation == 0 || operation == 1) {
                mDatas.clear();
                mDatas.addAll(offlineDetectionData.getOffLineTaskList());
                operation = 0;
            }
            adapter.UpDateList(mDatas);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showOffLineMoreData(OfflineDetectionData offlineDetectionData) {
        if (offlineDetectionData.getOffLineTaskList().size() == 0) {
            fastOnlineRecycler.setAdapterLastState(RefreshRecycleView.STATE_NO_MORE);
        } else {
            mDatas.addAll(offlineDetectionData.getOffLineTaskList());
            adapter.UpDateList(mDatas);
            adapter.notifyDataSetChanged();
            fastOnlineRecycler.setRefreshing(false);
            fastOnlineRecycler.setAdapterLastState(RefreshRecycleView.STATE_UP_LOADEMORE);
        }
        operation = 0;
    }

    @Override
    public void onOnLineAndOffLineLoadDataError(String errMsg) {
        llError.setVisibility(View.VISIBLE);  //网络错误的时候，展示网络错误布局
        fastOnlineRecycler.setVisibility(View.GONE);
    }

    public void   cancle(View view){
        OffLineSearchByVINActivity.this.finish();
    }

    @Override
    public Map<String, String> getOffLineSearchByVinParameters(String pageId){
        Map<String, String> params = new HashMap<String, String>();
        params.put("op", "GetOffLineList");
        params.put("pageIndex", String.valueOf(PageIndex<1?1:PageIndex));
        params.put("userid",  user.getUserId() + "");
        params.put("datetype", datetype + "");
        params.put("status", status);
        params.put("Operation", operation + "");
        params.put("tokenid", "6");
        if (!TextUtils.isEmpty(pageId)) {
            params.put("PageId", pageId);
        }
        params.put("vin", vin);
        Map<String, Object> maps = new HashMap<>();
        maps.putAll(params);
        params.put("sign", MD5Utils.getMD5Sign(maps));
        return params;
    }

}
